package yl.hs.bmipfull.security;


import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import yl.hs.bmipfull.service.system.IOrganizationInfoService;
import yl.hs.bmipfull.service.system.IUserService;
import yl.hs.bmipfull.utils.HsApp;

/**
 * @author 华砂信息 <br/>
 * 身份验证
 */
public class AuthenticationProvider extends DaoAuthenticationProvider {


    public AuthenticationProvider(UserDetailsService userDetailsService,IOrganizationInfoService organizationInfoService) {
        setUserDetailsService(userDetailsService);
        //UsernamePasswordAuthenticationFilter as
        //setUserCache();
        HsApp.setUserService((IUserService) userDetailsService,organizationInfoService);

        setPasswordEncoder(new PasswordEncoder() {
            @Override
            public boolean matches(CharSequence rawPassword, String encodedPassword) {
                var radpwd = MD5.getMD5(rawPassword.toString());
                return radpwd.equals(encodedPassword);
            }

            @Override
            public String encode(CharSequence rawPassword) {
                return MD5.getMD5(rawPassword.toString());
            }
        });
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        // 可以在此处覆写整个登录认证逻辑
        return super.authenticate(authentication);
    }

    @Override
    protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication)
            throws AuthenticationException {

        // 可以在此处覆写密码验证逻辑
        super.additionalAuthenticationChecks(userDetails, authentication);
    }
}
